package com.zz.common.tools.box.tools;

import java.io.ByteArrayInputStream;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.ContentHandler;
import org.xml.sax.InputSource;
import org.xml.sax.Locator;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;

public abstract class BpXMLParser extends IBpDataLoaderParser implements ContentHandler{
	protected Object mResult;
	protected StringBuilder mBuffer = new StringBuilder();
	
	@Override
	public final Object parse(byte[] b) {
		SAXParserFactory factory=SAXParserFactory.newInstance(); 
	     try {            
	    	 SAXParser parser=factory.newSAXParser();              
	    	 XMLReader xmlReader=parser.getXMLReader();                     
	    	 xmlReader.setContentHandler(this);    
	    	 xmlReader.parse(new InputSource(new ByteArrayInputStream(b)));
	     } catch(Exception ex) {
	    	 mErrCode = BpDataLoader.DATA_LOADER_PARSE_ERROR;
	    	 mResult = null;
	     }
	     
	     return mResult;
	}
	
	@Override
	public void startDocument () throws SAXException {
	}
	
	@Override
	public void startElement (String uri, String localName,
            String qName, Attributes atts) throws SAXException {
	}
	
	@Override
	public void characters (char ch[], int start, int length) throws SAXException {
		mBuffer.append(ch, start, length);
	}
	
	@Override
	public void endElement (String uri, String localName,
            String qName) throws SAXException {
		mBuffer.setLength(0);
	}
	
	@Override
	public void endDocument() throws SAXException {
	}
	
	@Override
	public void startPrefixMapping(String prefix, String uri)
			throws SAXException {
	}
	
	@Override
	public void skippedEntity(String name) throws SAXException {
	}
	
	@Override
	public void setDocumentLocator(Locator locator) {
	}
	
	@Override
	public void processingInstruction(String target, String data)
			throws SAXException {
	}
	
	@Override
	public void ignorableWhitespace(char[] ch, int start, int length)
			throws SAXException {
	}
	
	@Override
	public void endPrefixMapping(String prefix) throws SAXException {
	}
}
